package cn.t.web.ent;

import cn.t.constants.CommonConstants;
import cn.t.constants.ResponseError;
import cn.t.converter.user.UserInfoRequestConverter;
import cn.t.core.exception.BizException;
import cn.t.core.mode.PageInfoDTO;
import cn.t.core.mode.PageQueryDTO;
import cn.t.dto.api.OpenDoorRequestDTO;
import cn.t.dto.user.CreateUserRequest;
import cn.t.dto.user.CustomerFirmDTO;
import cn.t.dto.user.CustomerIndividualDTO;
import cn.t.dto.user.ImportUserRequest;
import cn.t.dto.user.ParticipantInfoDTO;
import cn.t.dto.user.RoleInfoDTO;
import cn.t.dto.user.UpdateUserRequest;
import cn.t.dto.user.UserInfoDTO;
import cn.t.dto.user.UserPassportDTO;
import cn.t.dto.user.UserQueryDTO;
import cn.t.core.enums.base.CommonError;
import cn.t.facade.user.ParticipantRoleFacade;
import cn.t.facade.user.UserInfoFacade;
import cn.t.facade.user.UserLoginFacade;
import cn.t.facade.user.UserQueryFacade;
import cn.t.facade.user.WrappedEnterpriseFacade;
import cn.t.response.ResultDTO;
import cn.t.utils.RequestUtil;
import cn.t.vo.ent.EntUserOverviewVO;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 企业站-领料员管理
 */
@Slf4j
@RestController
@RequestMapping("/ent/user")
@AllArgsConstructor
public class EntUserController {

    private final WrappedEnterpriseFacade wrappedEnterpriseFacade;
    private final UserQueryFacade userQueryFacade;
    private final UserInfoFacade userInfoFacade;
    private final UserLoginFacade userLoginFacade;
    private final UserInfoRequestConverter userInfoRequestConverter;
    private final ParticipantRoleFacade participantRoleFacade;
    /**
     * 领料员列表
     */
    @PostMapping({"/page"})
    public PageInfoDTO<UserQueryDTO> findByPage(@RequestBody PageQueryDTO<UserQueryDTO> queryDTO) {
        return this.userQueryFacade.findEntUserPage(queryDTO);
    }

    /**
     * Excel 导入用户
     */
    @PostMapping("/import")
    public void importUserInfo(@RequestParam(required = false) MultipartFile excel) {

        List<ImportUserRequest> excelDataList = null;

        String firmCode = RequestUtil.getHeaderVal(CommonConstants.CUSTOMER_CODE);

        try {
            byte[] data = excel.getBytes();
            excelDataList = EasyExcelFactory.read(new ByteArrayInputStream(data), new AnalysisEventListener<ImportUserRequest>() {
                @Override
                public void invoke(ImportUserRequest request, AnalysisContext analysisContext) {
                    List<String> results = wrappedEnterpriseFacade.validateImportUserRequest(firmCode, request);
                    if (!CollectionUtils.isEmpty(results)) {
                        StringBuilder errorMessage = new StringBuilder();
                        for (String str : results) {
                            errorMessage.append(str).append("\n");
                        }
                        throw new BizException(ResponseError.DATA_ERR, "格式错误：请检查第" + analysisContext.readRowHolder().getRowIndex() + "行数据。" + errorMessage.toString());
                    }
                }

                @Override
                public void onException(Exception exception, AnalysisContext context) {
                    // 如果异常是ExcelDataConvertException，则是格式错误
                    if (exception instanceof ExcelDataConvertException) {
                        throw new BizException(ResponseError.DATA_ERR, "格式错误：请检查第" + context.readRowHolder().getRowIndex() + "行数据。" + "行数据的格式是否正确。");
                    } else {
                        // 其他类型的异常
                        log.error("导入失败，失败原因：{}", exception.getMessage(), exception);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }

            }).head(ImportUserRequest.class).ignoreEmptyRow(true).doReadAllSync();

        } catch (IOException e) {
            log.error("文件处理过程中IO 异常", e);
        }

        wrappedEnterpriseFacade.importUserInfo(excelDataList);
    }

    /**
     * 创建领料员
     */
    @PostMapping("/create")
    public UserInfoDTO createUser(@Validated @RequestBody CreateUserRequest request) {

        Map<Integer, UserPassportDTO> passportMap = userInfoRequestConverter.convertPassport(request);


        if (passportMap == null || passportMap.isEmpty()) {
            throw new BizException(CommonError.ILLEGAL_PARAMETER, "通行证参数为空");
        }

        UserInfoDTO userInfo = userInfoRequestConverter.convertUserInfo(request);
        CustomerIndividualDTO customerIndividual = userInfoRequestConverter.convertCustomerInfo(request);
        ParticipantInfoDTO participantInfoDTO = userInfoRequestConverter.convertParticipantInfo(request);
        RoleInfoDTO roleInfoDTO = userInfoRequestConverter.convertRoleInfoDTO(request);

        return userInfoFacade.create(passportMap, userInfo, participantInfoDTO, roleInfoDTO, customerIndividual, null);
    }

    /**
     * 企业站用户屏蔽
     */
    @PostMapping("/disable")
    public boolean disableUser(Long userId) {
        return userInfoFacade.disableUser(userId);
    }

    /**
     * 企业站用户启用
     */
    @PostMapping("/enable")
    public boolean enableUser(Long userId) {
        return userInfoFacade.enableUser(userId);
    }

    /**
     * 企业站用户修改
     */
    @PostMapping("/update")
    public UserInfoDTO updateUser(@Validated @RequestBody UpdateUserRequest request) {
        Map<Integer, UserPassportDTO> passportMap = userInfoRequestConverter.convertPassport(request);
        UserInfoDTO userInfo = userInfoRequestConverter.convertUserInfo(request);
        CustomerIndividualDTO customerIndividual = userInfoRequestConverter.convertCustomerInfo(request);
        ParticipantInfoDTO participantInfoDTO = userInfoRequestConverter.convertParticipantInfo(request);
        CustomerFirmDTO customerFirmDTO = userInfoRequestConverter.convertCustomerFirm(request);
        RoleInfoDTO roleInfoDTO = userInfoRequestConverter.convertRoleInfoDTO(request);
        userInfoFacade.update(passportMap, userInfo, participantInfoDTO, customerIndividual, customerFirmDTO);
       //修改角色
        List<RoleInfoDTO> roleList =new ArrayList<>();
        if (roleInfoDTO!=null){
            roleList.add(roleInfoDTO);
        }

        participantRoleFacade.assignRights(userInfo, roleList);
        return userInfoFacade.queryOne(request.getUserId());

    }

    /**
     * 领料员统计接口
     */
    @GetMapping("/overview")
    public EntUserOverviewVO overview(@RequestParam Long firmId) {
        return userInfoFacade.overview(firmId);
    }



}

